<template>
  <el-card class="box-card">
    <div slot="header">
      <span>读者管理</span>
      <el-button size="mini" type="primary" class="el-icon-plus" @click="addUserBtnFn" style="float: right">
        添加
      </el-button>
    </div>
    <div class="table_list">
      <el-table :data="tableData" style="width: 100%" :max-height="$store.state.tableHeight">
        <el-table-column prop="userid" label="账号" width="100px"></el-table-column>
        <el-table-column prop="username" label="昵称" width="150px"></el-table-column>
        <el-table-column prop="password" label="密码" width="150px"></el-table-column>
        <el-table-column prop="sex" label="性别" width="100px"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="联系方式"></el-table-column>
        <el-table-column prop="role" label="权限" width="80">
          <template v-slot="scope">
            <el-tag v-if="scope.row.role == 2">读者</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="状态" width="80">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status == 0" type="danger">禁用</el-tag>
            <el-tag v-else type="success">启用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateUserBtnFn(scope.row)">编辑</el-button>
            <el-popconfirm confirm-button-text="好的" cancel-button-text="不用了" icon="el-icon-info" icon-color="red"
              title="这是一段内容确定删除吗？" @confirm="delUserBtnFn(scope.row.id)">
              <el-button type="danger" slot="reference" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="isEdit ? '编辑读者' : '添加读者'" :visible.sync="dialogVisible" width="50%" :before-close="handleClose"
      @closed="addCloseFn">
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" class="demo-ruleForm">
        <div class="dialog-box">
          <div class="dialog-left">
            <el-form-item label="账号" prop="userid" label-width="70px">
              <el-input v-model="userForm.userid" disabled></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="username" label-width="70px">
              <el-input v-model="userForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="70px">
              <el-input v-model="userForm.password"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex" label-width="70px">
              <el-select v-model="userForm.sex" placeholder="请选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" label-width="70px">
              <el-input v-model="userForm.email"></el-input>
            </el-form-item>
          </div>
          <div class="dialog-right">
            <el-form-item label="联系方式" prop="phone" label-width="80px">
              <el-input v-model="userForm.phone" maxlength="11"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onsubmit">确 定</el-button>
      </span>
    </el-dialog>
    <Pagination :total="total" @pagination="handlePageChange" />
  </el-card>
</template>

<script>
import Pagination from "@/components/Pagination.vue";
import { getUserListAPI, addUserAPI, uptUserAPI, delUserAPI } from "@/api";
import { customAlphabet } from "nanoid";
export default {
  components: { Pagination },
  data() {
    return {
      // 分页
      total: 0,
      pagenum: 1,
      pagesize: 9,
      editId: "",
      isEdit: false,
      dialogVisible: false,
      tableData: [],
      userForm: {
        userid: '',
        username: "",
        password: "",
        email: "",
        sex: "",
        phone: "",
      },
      rules: {
        phone: [
          { required: true, message: "手机号不能为空" },
          {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: "手机号格式不对",
            trigger: "blur",
          },
        ],
        id_card: [
          { required: true, message: "身份证号不能为空" },
          { type: "string", message: "身份号必须为数字" },
          {
            pattern:
              /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "不是合法的身份证号！",
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 3, message: "长度在 2 到 3 个字符", trigger: "blur" },
        ],
        student_id: [
          { required: true, message: "请输入学号", trigger: "blur" },
          {
            min: 11,
            max: 20,
            message: "长度在 11 到 20 个字符",
            trigger: "blur",
          },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        class: [
          { required: true, message: "请输入班级", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 分页
    handlePageChange(obj) {
      console.log(obj);
      this.pagenum = obj.pagenum;
      this.pagesize = obj.pagesize;
      this.getUserListFn();
    },
    // 获取读者列表
    async getUserListFn() {
      // console.log(this);
      const res = await getUserListAPI(this.pagenum, this.pagesize);
      this.tableData = res.data.data;
      this.total = res.data.total;
      console.log(res.data);
    },
    // 更新读者
    updateUserBtnFn(obj) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.editId = obj.id;
      this.$nextTick(() => {
        //   数据回显  在打开修改对话框的时候 里面有数据
        this.userForm.userid = obj.userid;
        this.userForm.username = obj.username;
        this.userForm.password = obj.password;
        this.userForm.sex = obj.sex;
        this.userForm.email = obj.email;
        this.userForm.phone = obj.phone;
      });
    },
    // 添加读者
    addUserBtnFn() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.editId = "";
      const nanoid = customAlphabet('1234567890', 6)
      this.userForm.userid = nanoid()
    },
    // 提交 更新、添加 读者 调用api
    onsubmit() {
      this.$refs.userFormRef.validate(async (valid) => {
        if (valid) {
          // 进行 添加 / 更新
          if (this.isEdit) {
            const obj = { ...this.userForm, id: this.editId };
            const res = await uptUserAPI(obj);
            if (res.data.status === 0) {
              this.$message.success("更新读者信息成功！");
            } else {
              this.$message.error("添加读者失败！");
            }
          } else {
            const res = await addUserAPI(this.userForm);
            if (res.data.status === 0) {
              this.$message.success("添加读者成功！");
            } else {
              this.$message.error("添加读者失败！");
            }
          }
          this.getUserListFn();
          this.dialogVisible = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除读者
    async delUserBtnFn(id) {
      const res = await delUserAPI(id);
      if (res.data.status === 0) {
        this.$message.success("删除读者成功！");
      } else {
        this.$message.error("删除读者失败！");
      }
      this.getUserListFn();
    },
    addCloseFn() {
      this.$refs.userFormRef.resetFields();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
  },
  mounted() {
    this.getUserListFn();
  },
};
</script>

<style scoped>
.dialog-box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.dialog-left,
.dialog-right {
  width: 350px;
}
</style>
